/**
 * DataTable Modules.
 * Date: 2015/04/09.
 */
define([
	'jquery',
	'datatables',
	'dataTables_bs',
	'dataTables_rsp',
	'dataTables_fh',
	'tableColumnResize',
	'store',
	'languageMap'
], function($, datatables, dataTables_bs, dataTables_rsp, dataTables_fh, TableColumnResize, store, languageMap) {
	var VamDataTable = {};

	VamDataTable = (function() {
		// Constructor
		function VamDataTable () {
			this.settings = {};
			this.listTable = {};
			this.tableColumnInit = [];
			this.tableColumnVisible = [];
		}
		VamDataTable.prototype.defaults = {
			"dom": "<'dataTables_length table-column-filter-wrap'>lrftip",
			// 'deferRender': true,
			"autoWidth": false,
			// "stateSave": true,
			// "responsive": true,
			"lengthMenu": [
				[15, 30, 50, 100],
				[15, 30, 50, 100]
			],
			"language": {
		    "sProcessing":   VAM.j('Processing'),
		    "sLengthMenu":   VAM.j('Show _MENU_ entries'),
		    "sZeroRecords":  VAM.j('No matching records found'),
		    "sInfo":         VAM.j('Showing _START_ to _END_ of _TOTAL_ entries'),
		    "sInfoEmpty":    VAM.j('Showing 0 to 0 of 0 entries'),
		    "sInfoFiltered": VAM.j('(filtered from _MAX_ total entries)'),
			  "sInfoPostFix":  "",
		    "sSearch":       VAM.j('Search:'),
		    "sSearchPlaceholder": VAM.j('Search...'),
		    "sUrl":          "",
		    "sEmptyTable":     VAM.j('No data available in table'),
		    "sLoadingRecords": VAM.j('<i class=\"fa fa-spinner fa-spin\"></i> loading...'),
		    "sInfoThousands":  ",",
		    "oPaginate": {
	        "sFirst":    VAM.j('First'),
	        "sPrevious": VAM.j('Previous'),
	        "sNext":     VAM.j('Next'),
	        "sLast":     VAM.j('Last')
		    },
		    "oAria": {
	        "sSortAscending":  VAM.j('activate to sort column ascending'),
	        "sSortDescending": VAM.j('activate to sort column descending')
		    }
			},
			'vamSettings': {
				'vamListDateFilter': true,
        'vamColumnFilter': true,
        'vamColumnStore': true,
        'vamColumnOperate': false,
        'vamColumnResize': {
        	'resize': true,
        	'adjust': true
        }
      }
		};
		VamDataTable.prototype.init = function(options) {
			$.extend(true, this.settings, this.defaults, options);
		};
		VamDataTable.prototype.refresh = function(listTable) {
			var $dataRefreshBtn = $('.data-table-refresh'),
				$icon = $dataRefreshBtn.find('.fa');
			$dataRefreshBtn.on('click', function (evt) {
				evt.preventDefault();
				$icon.addClass('fa-spin');
				listTable.ajax.reload(function () {
					$icon.removeClass('fa-spin');
				});
			});
		};
		VamDataTable.prototype.reload = function(listTable) {
			listTable.ajax.reload();
		};
		VamDataTable.prototype.listDataFilter = function($dataTable, listTable) {
			if (!this.settings['vamSettings']['vamListDateFilter']) {
				return;
			}
			$dataTable.on('change keyup', 'input.table-head-filter', function(evt) {
	      var $me = $(this),
	        index = $me.data('index'),
	        meVal = $me.val();
	      evt.preventDefault();
	      listTable.column(index).search(meVal).draw()
	    });
		};
		VamDataTable.prototype.columnFilter = function($table, listTable) {
			if (!this.settings['vamSettings']['vamColumnFilter']) {
				return;
			}
			var $tableColumnFilterWrap = $('.table-column-filter-wrap'),
				columnCkbStr = '',
				columnFilterStr,
				columnFilterWrap,
				that = this;
			columnFilterStr = '<button type="button" class="btn btn-default btn-sm table-filter-btn"><i class="fa fa-filter"></i> ' + VAM.j('Column Filter') + ' <span class="caret"></span></button>';
			$tableColumnFilterWrap.append(columnFilterStr);

			// Column filter radiobox.
			this.$tableThs.each(function(index, el) {
				var $me = $(this),
					fitler = $me.data('filter'),
					visible = listTable.column(index).visible(),
					ckbStatus = !that.tableColumnVisible[index] ? 'checked' : '';

				if (fitler !== 'off') {
					// if (that.tableColumnInit[index]) {
					// 	columnCkbStr += '';
					// } else {
					// 	columnCkbStr += '<li><div class="checkbox"><label><input type="checkbox" ' + ckbStatus + ' data-column="' + index + '">' + $me.text() + '</label></div></li>';
					// }
					columnCkbStr += '<li><div class="checkbox"><label><input type="checkbox" ' + ckbStatus + ' data-column="' + index + '">' + $me.text() + '</label></div></li>';
				}
			});
			columnFilterWrap = '<div class="popover bottom" role="tooltip" style="top: 100%; left: 0px;"><div class="arrow" style="left: 41px;"></div><h3 class="popover-title">' + VAM.j('Table Filter') + '</h3><div class="popover-content"><ul class="list-unstyled" id="column-filter">' + columnCkbStr + '</ul></div></div>';
			$('.table-filter-btn').after(columnFilterWrap);
			// Column filter wrap toggle.
			$tableColumnFilterWrap.on('click', '.table-filter-btn', function(evt) {
				var $me = $(this),
					$tableFilterPop = $me.siblings('.popover');
					$tableFilterPop.slideToggle('fast');
			});
			// Column filter.
			$tableColumnFilterWrap.on('change', '#column-filter input', function(evt) {
				var $me = $(this),
					$tableFilterThs,
					filterStatus = '',
					index = $me.data('column'),
					column = listTable.column(index),
					columnHeader = column.header();
					$tableFilterThs = $table.find('thead > tr > td');
				evt.preventDefault();
				column.visible(!column.visible());
				if ($tableFilterThs.length > 0) {
					if (!column.visible()) {
						filterStatus = 'none';
					};
					filterStatus = !column.visible() ? 'none' : 'table-cell';
					$tableFilterThs.eq(index).css('display', filterStatus);
				}
				$table.css('width', 'auto');
				$(window).trigger('resize');
				// that.columnResize($table);
				if (column.visible()) {
					that.tableColumnVisible[index] = 0;
				} else {
					that.tableColumnVisible[index] = 1;
				};
	      if ($(columnHeader).data('switch')) {
	      	var $switchBtn = $('.switch-column').find('input[type="checkbox"]');
	        $switchBtn.bootstrapSwitch({
	          onText: VAM.j('ON'),
	          offText: VAM.j('OFF'),
	          labelWidth: 10
	        });
	      };
				that.updateVisibleData();
				that.switchFilterStatus();
			});

			$tableColumnFilterWrap.on('mouseleave', 'div.popover', function(evt) {
				var $me = $(this);
				evt.preventDefault();
				$me.slideUp('fast');
			});
			// Set filter button status.
			this.switchFilterStatus();
		};
		VamDataTable.prototype.columnResize = function($table, options) {
			$table.css('width', 'auto');
			this.init(options);
			var tableColumnResize,
				adjustHeight = $table.siblings('.dataTables_filter').height();

			// $table.siblings('.rc-handle-container').remove();
			if (!this.settings['vamSettings']['vamColumnResize']['resize']) {
				return;
			}
			tableColumnResize = new TableColumnResize($table, {
				resizeFromBody: false
			});
			if (this.settings['vamSettings']['vamColumnResize']['adjust']) {
				$table.siblings('.rc-handle-container').css('top', adjustHeight);
			}

			window.onresize = tableColumnResize.syncHandleWidths.bind(tableColumnResize);
			$(window).on('resize', function () {
				$table.css('width', 'auto');
        var newTabWth = $table.width(),
          tabWrapperWth = $('.dataTables_wrapper').width();
        if ((tabWrapperWth+5) > newTabWth) {
          $table.css('width','100%');
        } else {
          $table.width(newTabWth);
        };
			})

			$(window).trigger('resize');
		};
		VamDataTable.prototype.columnOperate = function($table) {
			if (this.settings['vamSettings']['vamColumnOperate'] === false) {
				return;
			}
			var $tableColumnOperate = $('.table-operate-wrap');
			$tableColumnOperate.append(this.settings['vamSettings']['vamColumnOperate']);
		};
		VamDataTable.prototype.listCascade = function($table) {
			var $ckbAll = $table.find('.tab-ckb-all');
			$ckbAll.on( 'click', function(){
				$childCheck = $('.tab-ckb-sub');
				for (var i = 0, l = $childCheck.length; i < l; i++){
					$childCheck[i].checked = $ckbAll.get(0).checked;
				}
			});
			// Child cascade all.
			$table.on('click', '.tab-ckb-sub', function(){
				var allChecked = true,
				    $childCheck = $('.tab-ckb-sub');
				if (this.checked){
					for (var i = 0, l = $childCheck.length; i<l; i++) {
						if (!$childCheck[i].checked){
							allChecked = false;
							break;
						}
					}
					if (allChecked && !$ckbAll.get(0).checked) {
						$ckbAll.get(0).checked = true;
					}
				} else {
					if ( $ckbAll.get(0).checked ) {
						$ckbAll.get(0).checked = false;
					}
				}
			});
		};
		VamDataTable.prototype.listVisibleInit = function ($table) {
			var tagId = this.tableTag,
          tdStr = '',
          filterRow = '',
					$reportDataThead = $table.find('thead'),
				columnVisibleInitData = store.get(tagId) || [];
			// 0 -- visible, 1 -- inviiable
			for (var i = 0, len = this.$tableThs.length; i < len; i++) {
				var iStatus = columnVisibleInitData[i] || 0,
					storeConfig = this.settings['vamSettings']['vamColumnStore'],
					iInitStatus = this.listTable.column(i).visible() ? 0 : 1;
				if (!storeConfig) {
					iStatus = 0;
				}
				this.tableColumnInit.push(iInitStatus);
				this.tableColumnVisible.push(iStatus);

			};

			for (var j = 0, l = this.tableColumnVisible.length; j < l; j++) {
				var jStatus = this.tableColumnVisible[j] ? false : true,
					jColumn = this.listTable.column(j),
					jVisible = jColumn.visible(),
					filterStatus = '',
					searchFlag = this.$tableThs.eq(j).data('search'),
					inputStr = '',
					jSetVisible = jStatus && jVisible;

				filterStatus = !jSetVisible ? 'none' : 'table-cell';
				jColumn.visible(jSetVisible);

				// Search Input
        if (searchFlag === 'on') {
          inputStr = '<input type="text" class="form-control input-sm table-head-filter" data-index="' + j + '" placeholder="' + this.$tableThs.eq(j).text() + '">';
        } else {
          inputStr = '';
        }
        tdStr = '<td style="display: ' + filterStatus + '">'
              + inputStr
              + '</td>';
        filterRow += tdStr;
			};
			if (this.settings['vamSettings']['vamListDateFilter']) {
				filterRow = '<tr role="row">' + filterRow + '</tr>';
	      $reportDataThead.append(filterRow);
			};
		}
		VamDataTable.prototype.updateVisibleData = function () {
			var tagId = this.tableTag,
				storeConfig = this.settings['vamSettings']['vamColumnStore'];
			// console.log(tagId);
			if (!tagId || !storeConfig) {
				return;
			}
			// console.log(this.tableColumnVisible);
			store.set(tagId, this.tableColumnVisible);
		};
		VamDataTable.prototype.switchFilterStatus = function () {
			var $columnFilterList = $('#column-filter input'),
					$tableFilterBtn = $('.table-filter-btn');
			// console.log($columnFilterList.length);
			// console.log($columnFilterList.filter('input:checked').length);
			if ($columnFilterList.length !== $columnFilterList.filter('input:checked').length) {
				$tableFilterBtn.addClass('btn-warning');
			} else {
				$tableFilterBtn.removeClass('btn-warning');
			}
		};
		VamDataTable.prototype.setTableWidth = function ($table) {
			var tableWidth = this.settings['width'];
			if (!tableWidth) {
				return;
			}
			$table.css('width',tableWidth);
		};
		VamDataTable.prototype.dataTables = function($table, options) {
			this.$tableThs = $table.find('thead > tr > th');
			this.tableTag = $table.data('tag');
			this.init(options);
			this.listTable = $table.DataTable(this.settings);
			this.setTableWidth($table);
			this.refresh(this.listTable);
			this.listVisibleInit($table);
			this.columnFilter($table, this.listTable);
			// this.columnResize($table);
			this.columnOperate($table);
			this.listDataFilter($table, this.listTable);
			this.listCascade($table);
			return this.listTable;
		};

		// Return class.
		return VamDataTable;
	})();

	return VamDataTable;
});
